<template>
  <div v-drag class="drag" @click="handleClick"><slot></slot></div>
</template>

<script>
export default {
  name: "drag",
  directives: {
    drag: function(el) {
      let dragBox = el; //获取当前元素
      let moveW = 0; //移动元素的width
      let moveH = 0; //移动元素的height

      let parentElementHeight = 0; //父盒子的高度
      dragBox.onmousedown = (e) => {
        moveW = dragBox.offsetWidth;
        moveH = dragBox.offsetHeight;
        //算出鼠标相对元素的位置
        let disX = e.clientX - dragBox.offsetLeft;
        let disY = e.clientY - dragBox.offsetTop;
        let pWidth = dragBox.parentElement.parentElement.offsetWidth; //父盒子的宽度
        let pHeight = dragBox.parentElement.parentElement.offsetHeight;
        document.onmousemove = (e) => {
          //用鼠标的位置减去鼠标相对元素的位置，得到元素的位置
          let left = e.clientX - disX;
          let top = e.clientY - disY;
          let resW = pWidth - moveW; //父盒子宽减去移动盒子的宽 = 最大可移动的区域
          let resH = pHeight - moveH; //父盒子高减去移动盒子的高 = 可最大移动的区域
          left = left >= resW ? resW : left <= 0 ? 0 : left;
          top = top >= resH ? resH : top <= 0 ? 0 : top;
          //移动当前元素
          dragBox.style.left = left + "px";
          dragBox.style.top = top + "px";
        };
        document.onmouseup = (e) => {
          //鼠标弹起来的时候不再移动
          document.onmousemove = null;
          //预防鼠标放上去的时候还会移动
          document.onmouseup = null;
        };
      };
    },
  },
  methods: {
    handleClick(event) {
      this.$emit("dbclick", event);
    },
  },
};
</script>

<style scoped lang="scss">
.drag {
  cursor: move;
  position: absolute;
}
</style>
